package spring.cloud.tasks.tasks_manager.task_item_assign.pick_up.executor.task;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.common.curator.Curator;
import spring.cloud.tasks.common.task_item_allot.Executor;
import spring.cloud.tasks.common.task_item_allot.TaskItem;
import spring.cloud.tasks.tasks_manager.task_item_assign.PreferExecutorSettings;
import spring.cloud.tasks.tasks_manager.task_item_assign.pick_up.PickUp;

import java.util.Iterator;
import java.util.List;

/**
 * 任务的executor下线，将该executor运行的该任务分片都摘取，如果是本地任务，则移除
 */
@Slf4j
@Setter
@Getter
public class PickUpWhenTaskExecutorOffline extends PickUp {

    private String taskId;

    private String executorId;


    @Override
    protected void log() {
        log.info("Execute the {}, taskId is {}, executorName is {}", this.getClass().getSimpleName(), taskId, executorId);
    }

    @Override
    public boolean pickUp(Curator curator,//
                          List<String> taskIdList,//
                          List<String> enableTaskIdList,//
                          List<TaskItem> pickUpEdTaskItemList,//
                          List<TaskItem> discardTaskItemList,//
                          List<Executor> onlineExecutorList,//
                          List<Executor> ownTrafficOnlineExecutorList,//
                          PreferExecutorSettings preferExecutorSettings) throws Exception {
        for (int i = 0; i < onlineExecutorList.size(); i++) {
            Executor onlineExecutor = onlineExecutorList.get(i);
            if (onlineExecutor.getExecutorId().equals(executorId)) {
                onlineExecutor.getTaskIdList().remove(taskId);
                Iterator<TaskItem> iterator = onlineExecutor.getTaskItemList().iterator();
                while (iterator.hasNext()) {
                    TaskItem taskItem = iterator.next();
                    if (taskItem.getTaskId().equals(taskId)) {
                        pickUpEdTaskItemList.add(taskItem);
                        iterator.remove();
                    }
                }
                break;
            }

        }
        return true;
    }


}
